﻿using Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WsdShop.IService;
using WsdShop.Model;
using WsdShop.Model.SearchModels.Draw;
using WsdShop.Service;
using WsdShop.Model.Enum;
using WsdShop.Model.ViewModels;

namespace Admin.Controllers
{
    public class DrawController : BaseController
    {
        #region 构造
        private IDrawAdminService drawAdminService;
        private ICouponService couponService;

        public DrawController(IUserInfoService s,IDrawAdminService d,ICouponService c) : base(s)
        {
            drawAdminService = d;
            couponService = c;
        }
        #endregion

        #region 抽奖活动

        [HttpGet]
        public ActionResult DrawList()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DrawList(DrawSearchModel search)
        {
            int total = 0;
            var list = drawAdminService.GetDrawList(search, out total);
            return Json(new { Total = total, Results = list });
        }

        //修改或新增积分抽奖
        public ActionResult DrawEdit()
        {
            return View();
        }

        //上下架操作
        public ActionResult ModifyDrawStatus(int id,bool isDisplay)
        {
            var model = BaseService.LoadEntity<Draw>(d => d.Id == id);
            if (model == null)
                return Json(Result.Failure("未找到该活动"));
            try
            {
                //如果上架操作，则判断奖项数量
                if (isDisplay)
                {
                    int prizeNum = BaseService.LoadEntitiesCount<DrawReward>(d => d.DrawId == id && d.IsDeleted == false);
                    if (prizeNum <= 0)
                    {
                        return Json(Result.Failure("请至少保证有一个奖项，本活动才能上架！"));
                    }
                    if (prizeNum > 11)
                    {
                        return Json(Result.Failure("奖项数量不能超过11个！"));
                    }
                }
                model.IsDisplay = isDisplay;
                if (BaseService.UpdateEntity<Draw>(model))
                {
                    return Json(Result.Success("保存成功"));
                }
                else
                {
                    return Json(Result.Failure("保存失败"));
                }
            }
            catch(Exception ex)
            {
                return Json(Result.Failure(ex.Message));
            }
            
        }

        //删除操作
        public ActionResult DeleteDraw(int id)
        {
            var model = BaseService.LoadEntity<Draw>(d => d.Id == id);
            if (model == null)
                return Json(Result.Failure("未找到该活动"));
            try
            {
                model.IsDeleted = true;
                if (BaseService.UpdateEntity<Draw>(model))
                {
                    return Json(Result.Success("删除成功"));
                }
                else
                {
                    return Json(Result.Failure("删除失败"));
                }
            }
            catch (Exception ex)
            {
                return Json(Result.Failure(ex.Message));
            }
        }
        //保存活动
        public ActionResult SaveDraw(Draw draw)
        {
            if (draw.EndTime < draw.StartTime)
            {
                return Json(Result.Failure("活动开始时间必须比结束时间早"));
            }
            if (string.IsNullOrWhiteSpace(draw.DrawCover))
            {
                return Json(Result.Failure("请选择封面图片"));
            }
            if (draw.ConsumePoints <= 0)
            {
                return Json(Result.Failure("积分消耗必须大于0"));
            }
            if (draw.Chances < 0)
            {
                return Json(Result.Failure("请输入正确的抽奖次数"));
            }
            //Id>0则为修改
            if (draw.Id > 0)
            {
                draw.EditTime = DateTime.Now;
                draw.EditUserId = CurrentLoginUser.Id;
                draw.IsDisplay = false;
                if (BaseService.UpdateEntity(draw))
                    return Json(Result.Success("保存成功"));
                else
                    return Json(Result.Failure("保存失败"));
            }
            else
            {
                draw.AddTime = DateTime.Now;
                draw.AddUserId = CurrentLoginUser.Id;
                draw.IsDeleted = false;
                draw.IsDisplay = false;//新创建的活动统一是下架状态
                BaseService.AddEntity(draw);
                return Json(Result.Success("添加成功"));
            }
        }

        //奖项编辑列表页
        public ActionResult DrawRewardEdit()
        {
            return View();
        }

        public ActionResult DrawRewardEditNew()
        {
            return View();
        }

        public ActionResult DrawRewardList(DrawRewardSearchModel search)
        {
            int total = 0;
            var model = drawAdminService.GetRewardList(search, out total);
            return Json(new { Total = total, Results = model });
        }

        public ActionResult DeleteReward(int id)
        {
            var model = BaseService.LoadEntity<DrawReward>(d => d.Id == id && d.IsDeleted == false);
            if(model == null)
            {
                return Json(Result.Failure("该奖项已删除，不能重复删除"));
            }
            try
            {
                model.IsDeleted = true;
                if (BaseService.UpdateEntity(model))
                {
                    return Json(Result.Success("删除成功"));
                }
                else
                {
                    return Json(Result.Failure("删除失败"));
                }
            }
            catch(Exception ex)
            {
                return Json(Result.Failure(ex.Message));
            }
            
        }

        //保存奖项
        public ActionResult SaveReward(DrawReward reward)
        {
            #region 常规检验
            if(reward.RewardType!=RewardType.优惠券&& reward.RewardType != RewardType.实体商品 && reward.RewardType != RewardType.奖励积分)
            {
                return Json(Result.Failure("请选择奖品类型"));
            }
            if (reward.Count <= 0)
            {
                return Json(Result.Failure("请填写正确的库存"));
            }
            if (reward.WinRate < 0 || reward.WinRate > 100)
            {
                return Json(Result.Failure("中奖几率必须在0~100之间"));
            }
            if (reward.RewardType==RewardType.奖励积分&&reward.Points <= 0)
            {
                return Json(Result.Failure("请填写正确的积分奖励"));
            }
            if (reward.RewardName.Length <= 0 || reward.RewardName.Length > 100)
            {
                return Json(Result.Failure("奖项名必须在1~100个字之内"));
            }
            if ((reward.RewardType == RewardType.实体商品 || reward.RewardType == RewardType.优惠券) && reward.ProductSecpId <= 0)
            {
                return Json(Result.Failure("请选择商品"));
            }

            if (reward.RewardType == RewardType.实体商品)
            {
                //var pro = BaseService.LoadEntity<Product>(p => p.Id == reward.ProductSecpId && p.IsDeleted == false && p.IsDisplay);
                var pro = drawAdminService.GetSpecById(reward.ProductSecpId);
                if (pro == null)
                {
                    return Json(Result.Failure("您选择的奖品已被删除或下架，请重新选择"));
                }
                reward.ProductName = pro.Name+' '+pro.SpecNames;
            }
            else if (reward.RewardType == RewardType.优惠券)
            {
                var cou = BaseService.LoadEntity<Coupon>(c => c.Id == reward.ProductSecpId && c.IsDeleted == false);
                if (cou == null)
                    return Json(Result.Failure("您选择的优惠券已被删除，请重新选择"));
                reward.ProductName = cou.CouponName;
            }
            else
            {
                reward.ProductName = "积分奖励";
            }
            #endregion
            //新增
            var result = new Result();
            if (reward.Id <= 0)
            {
                reward.AddTime = DateTime.Now;
                reward.AddUserId = CurrentLoginUser.Id;
            }
            else
            {
                reward.EditTime = DateTime.Now;
                reward.EditUserId = CurrentLoginUser.Id;
            }
            try
            {
                return Json(drawAdminService.SaveReward(reward, result));
            }
            catch(Exception ex)
            {
                return Json(Result.Failure(ex.Message));
            }          
        }

        //请求可用的商品数据(未被删除的和目前上架的)，供奖品选择
        public ActionResult GetActProducts()
        {
            var model = drawAdminService.GetActProducts();
            return Json(model);
        }
        //请求可用的优惠券数据
        public ActionResult GetActCoupons()
        {
            var model = drawAdminService.GetActCoupons();
            return Json(model);
        }

        public ActionResult GetDrawInfo(int Id=0)
        {
            if (Id == 0)
            {
                return null;
            }
            var model = BaseService.LoadEntity<Draw>(d=>d.Id==Id);
            return Json(model);
        }

        public ActionResult GetRewardInfo(int id=0)
        {
            if (id == 0)
            {
                return Json(new { Reward=new DrawReward(),ProductStep = new SpecResponse()});
            }
            var model = BaseService.LoadEntity<DrawReward>(d => d.Id == id);
            var proStep = new SpecResponse();
            if (model.RewardType == RewardType.实体商品&&model.ProductSecpId>0)
            {
                proStep = drawAdminService.GetSpecById(model.ProductSecpId);
            }
            return Json(new { Reward=model, ProductStep=proStep});
        }
        #endregion

        #region 抽奖记录
        public ActionResult DrawRecordList()
        {
            return View();
        }

        public ActionResult GetRecordList(DrawRecordSearchModel search)
        {
            int total = 0;
            var list = drawAdminService.GetRecordList(search, out total);
            return Json(new { Total = total, Results = list });
        }
        

        public ActionResult DeleteRecord(int id)
        {
            var model = BaseService.LoadEntity<DrawRecord>(d => d.Id == id);
            if (model == null)
                return Json(Result.Failure("未找到该条记录"));
            try
            {
                model.IsDeleted = true;
                if (BaseService.UpdateEntity<DrawRecord>(model))
                {
                    return Json(Result.Success("删除成功"));
                }
                else
                {
                    return Json(Result.Failure("删除失败"));
                }
            }
            catch (Exception ex)
            {
                return Json(Result.Failure(ex.Message));
            }
        }

        public ActionResult ModifyRecordStep(int id,StepType type)
        {
            try
            {
                var model = BaseService.LoadEntity<DrawRecord>(m => m.Id == id);
                if (model == null || model.RewardType != RewardType.实体商品)
                {
                    return Json(Result.Failure("该条记录无法做此操作！"));
                }
                if (model.StepType != StepType.已发放 && model.StepType != StepType.待发放)
                {
                    return Json(Result.Failure("用户未设置地址，无法作此操作！"));
                }
                model.StepType = type;

                if (BaseService.UpdateEntity(model))
                {
                    return Json(Result.Success("操作成功"));
                }
                else
                {
                    return Json(Result.Failure("操作失败"));
                }

            }
            catch(Exception ex)
            {
                return Json(Result.Failure(ex.Message));
            }
            
        }
        #endregion
    }
}